package com.sz.common.base.logger;

import ch.qos.logback.classic.spi.ILoggingEvent;
import com.sz.common.base.utils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Function: DbLogConsumer <br>
 * Author: Charles <br>
 * Date: 2016-12-01 12:27:00
 */
public class DbLogConsumer implements LogConsumer {

    private boolean restartClassLoaderExist = false;
    private String agentName;

    public DbLogConsumer(String agentName) {
        this.agentName = agentName;
        try {
            Class.forName("org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration");
            restartClassLoaderExist = true;
        } catch (ClassNotFoundException ex) {
            //do nothing
        }
    }

    @Override
    public void consumeLog(ILoggingEvent iLoggingEvent) {

        if (restartClassLoaderExist) { //only for dev
            consumeLogQuirks(iLoggingEvent);
            return;
        }
        DbLoggingService service = BeanUtils.getBean(DbLoggingService.class);
        if (service != null) {
            service.logging(getDomainId(), getAgentId(), iLoggingEvent);
        }
    }

    private int getDomainId() {
        return 1;
    }

    private String getAgentId() {
        return agentName;
    }

    /**
     * 消费日志（怪癖模式）
     *
     * @param iLoggingEvent
     */
    private void consumeLogQuirks(ILoggingEvent iLoggingEvent) {
        try {
            if (beanQuirks == null) {
                beanQuirks = getServiceBeanQuirks();
            }
            if (beanQuirks != null) {
                Method loggingMethod = beanQuirks.getClass().getMethod("logging", int.class, String.class, ILoggingEvent.class);
                loggingMethod.invoke(beanQuirks, getDomainId(), getAgentId(), iLoggingEvent);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }

    private Object beanQuirks = null;

    private Object getServiceBeanQuirks() {
        try {
            Class cls = Class.forName(BeanUtils.class.getName(), false, Thread.currentThread().getContextClassLoader());
            if (cls != null) {
                Method method = cls.getMethod("getBean", String.class);
                Object bean = method.invoke(null, "DbLoggingService");
                return bean;
            }
        } catch (ClassNotFoundException | NoSuchMethodException
                | IllegalAccessException | InvocationTargetException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
